<?php
include ('DataBase.php');
include_once ('DB_For_User.php');

class Authentication extends DataBase {

	const USERNAME = 'root';

	const PASSWORD = '';
	private $session_id;
	private $user_id;
	private $loginTimeAndDate; // ************ WIRD NOCH NOCHT BEACHTET**********
	private $email;
	private $password;
	private $browser;
	private $ip;
	private $user; // grant: -1 = not singnin, 0= vistor, 1= Inventor, 2= Admin
	public function __construct() {
		parent::__construct($this::USERNAME, $this::PASSWORD);
		$this->browser = substr($_SERVER['HTTP_USER_AGENT'], 0, 250);
		$this->ip = $_SERVER['REMOTE_ADDR'];
	}

	public function signin($source = '/index.php') {
		if(isset($_POST['submit'])) {
			// Es wird untersucht, ob in der Datenbank ein entsprechender User eingetragen ist, ansonsten wird eine Fehlermeldung
			// ausgegeben
			if(isset($_POST['email']) && isset($_POST['password'])) {
				// Hole die user-ID
				$this->email = $_POST['email'];
				$this->password = $_POST['password'];
				$dbForUser = new DB_For_User();
				if($dbForUser->getError()){
					HTML::dbNotAvailable();
				}
				$this->user_id = $dbForUser->getIdFromUser($this->email, $this->password);
				if(!is_null($this->user_id)) {
					$this->user = $dbForUser->getUserById($this->user_id);
					$_SESSION['user_ID'] = intval($this->user_id);
					$_SESSION['email'] = $this->email;
					
					
					// INFOS
					$this->loginTimeAndDate = strval(date("Y:m:d:H:i:s"));
					$this->session_id = session_ID();
					
					// UPDATE
					$this->insertAuthentication();
					$this->logginLogger($this->email, $this->password, 'SUCCESS');
					// session_write_close ();
					
					header('Location: ' . $source);
				} else {
					
					$this->logginLogger($this->email, $this->password, 'DENYED');
					echo '	<script type="text/javascript">
								alert("Falscher Benutzername oder Passwort");
							</script>';
					session_destroy();
					//header("Location: /signin.php");
				}
			} else {
				session_destroy();
				header("Location: /signin.php");
			}
		}
	}

	public function checkAuthentication($source, $grant) {
		// Kann innerhalb der Session auf eine Varioable idUser zur�ck gegriffen werden?
		if(isset($_SESSION['user_ID'])) {
			//echo(session_id());
			$id = session_id();
			$query = "SELECT * from authentication WHERE session_id = ? ORDER BY `login_timestamp` desc";
			$stmt = $this->db->prepare($query);
			if($stmt) {
				$stmt->bind_param('s', $id);
				if($stmt->execute()) {
					$result = $stmt->get_result();
					if($result) {
						if($result->num_rows > 0) {
							$row = $result->fetch_object();
							//print_r($row);
							//die();
							$dbUser_id = strval($row->user_user_id);
							$dbbrowser = strval($row->browser);
							$dbIP = strval($row->ip_adress);
							// $dbtime = strval ( $result->fetch_object ()->login_timestamp );
							// die($_SESSION['user_ID']);
							if(($dbUser_id != $_SESSION['user_ID']) || ($dbbrowser != $this->browser) || ($dbIP != $this->ip)) { // ||($dbtime != $this->loginTimeAndDate))) {
                                                                                                     //echo ($dbUser_id . "=" . $_SESSION['user_ID'] . "<br/>" . $dbbrowser . "=" . $this->browser . "<br/>" . $dbIP . "=" . $this->ip);
                                                                                                     // echo "hier";
                                                                                                     //die();
								session_destroy();
								//echo "Etwas wurde ver&auml;ndert";
								header("Location: /signin.php");
								// Irgendetwas stimmt nicht mehr, wurde ver�ndert, -> Zur�ck zum Login
							}
							$this->user = (new DB_For_USER())->getUserById($dbUser_id);
							
							// Benutzer registriert
							if($grant <= $this->user->getGrant()) {
								// zugriff gestatets
								return true;
							} else {
								// zugriff verweigert wegen zu wenigen rechten
								header('Location: /accessdenied.php');
							}
						} else {
							HTML::dbNotAvailable();
						}
					} else {
						HTML::dbNotAvailable();
					}
				} else {
					HTML::dbNotAvailable();
				}
			} else {
				HTML::dbNotAvailable();
			}
		} else {
			if($grant > -1) {
				session_destroy();
				header('Location: /signin.php?source=' . $source);
			} else {
				// g�ste erlaubt
				return true;
			}
		}
	}

	private function insertAuthentication() {
		try {
			$query = "INSERT INTO authentication (user_user_id, login_timestamp, session_id, ip_adress, browser) VALUES(?,?,?,?,?)";
			$stmt = $this->db->prepare($query);
			if($stmt) {
				$stmt->bind_param('issss', $this->user_id, $this->loginTimeAndDate, $this->session_id, $this->ip, $this->browser);
				if($stmt->execute()) {
					return true;
				}
			}
		} catch(Exception $e) {
			HTML::dbNotAvailable();
			return false;
		}
		HTML::dbNotAvailable();
		return false;
	}

	private function failAuthentication() {
		session_destroy();
		header("Location: /signin.php");
	}

	private function logginLogger($email, $password, $success) {
		// file basiert
	}

	public function getGrant() {
		return $this->user->getgrant();
	}

	public function getUser() {
		return $this->user;
	}
}

?>